package ioperations;

import book.Book;
import book.BookList;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 姚东名
 * Date: 2024-06-14
 * Time: 14:35
 */
public class DelOperation implements IOperation {
    @Override
    public void work(BookList bookList) {
        System.out.println("删除图书！");
        Scanner scanner = new Scanner(System.in);
        System.out.printf("请输入你要删除的书名：");
        String name = scanner.nextLine();

        int currentSize = bookList.getUsedSize();

        int pos = -1;
        int i = 0;
        //第一步：找到这本书
        for (; i < currentSize; i++) {
            Book book = bookList.getBook(i);
            if(book.getName().equals(name)) {
                pos = i;
                break;
            }
        }
        //假如走到最后还是没有找到要删除的图书，就结束程序
        if(currentSize == i) {
            System.out.println("没有你要删除的图书！");
        }

        //第二步：开始删除图书：
        for (int j = pos; j < currentSize - 1; j++) {//j < currentSize - 1 减1 是为了防止数组下标越界
            Book book = bookList.getBook(i);
            //从pos开始，把后一个元素覆盖前一个元素(图书)
            bookList.setBook(j, book);
        }

        //最后处理：使最后一个元素置为null
        bookList.setBook(currentSize - 1, null);
        //有效数据自减1
        bookList.setUsedSize(currentSize - 1);
        System.out.println("删除图书成功！");
    }
}
